import request from '../../utils/request'
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: app.globalData.userInfo
  },

  // 登录
  handleGetOpenId() {
    // 获取登录凭证
    wx.login({
      success: async(res) => {
        let code = res.code;
        let wechatUserVo = {
          avatarUrl: '',
          city: '',
          country: '',
          gender: '',
          language: '',
          nickName: '',
          province: '',
          code: ''
        };
        wx.getUserInfo({
          success: async(res) => {
            wechatUserVo = res.userInfo;
            wechatUserVo.code = code;
            // 将登录凭证发送服务器
            let result = await request('/auth/login', {
              wechatUserVo
            }, 'POST');
            let userInfo = this.data.userInfo;
            if (!userInfo) {
              wx.setStorageSync('userInfo', wechatUserVo);
              // 头部要带这个，所以设置缓存
              wx.setStorageSync('authorization', result.data);
              let userInfo = wx.getStorageSync('userInfo');
              if (userInfo) {
                this.setData({
                  userInfo
                })
              }
            }
            wx.showToast({
              title: '授权登录成功！'
            })
          }
        });

      }
    })
  },

  /**
   * 去“我的订单”页面
   */
  toMyOrder(data) {
    let orderStatus = data.currentTarget.dataset.id;
    this.validateUser('/orderPackage/pages/orderList/orderList?orderStatus=' + orderStatus);
    wx.navigateTo({
      url: '/orderPackage/pages/orderList/orderList?orderStatus=' + orderStatus
    })
  },

  /**
   * 去“我的地址”页面
   */
  toMyAddress() {
    this.validateUser('/addressPackage/pages/myAddress/myAddress');
    wx.navigateTo({
      url: '/addressPackage/pages/myAddress/myAddress'
    })
  },

  /**
   * 去“关于我们”页面
   */
  toAboutMe() {
    wx.navigateTo({
      url: '/otherPackage/pages/aboutme/aboutme'
    })
  },

  /**
   * 登录用户验证
   */
  validateUser(path) {
    let userInfo = wx.getStorageSync('userInfo');
    let authorization = wx.getStorageSync('authorization');
    if (!userInfo || !authorization || userInfo == undefined || authorization == undefined) {
      wx.navigateTo({
        url: '/pages/auth/auth?pageTo=' + path
      })
      return;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (app.globalData.userInfo && app.globalData.authorization) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.onLoad();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})